package sell

import (
	"adam2/internal/model"
	"adam2/internal/properties"
	"adam2/internal/util"
	"anubis-framework/pkg/io"
	"fmt"
	"gorm.io/gorm"
)

// 退市卖出
type CommonDelistSell struct {
	db *gorm.DB
}

// 初始化
func (c *CommonDelistSell) Init(db *gorm.DB) {
	c.db = db
}

// 卖出
func (c *CommonDelistSell) DoSell(transactionDate string) {
	io.Infoln("退市卖出")

	// quant_account表的所有记录
	var quantAccountArray model.QuantAccountArray
	c.db.Table("quant_account").Select("*").Order("id_ asc").Find(&quantAccountArray)

	for _, quantAccount := range quantAccountArray {
		// 如果这个账户没有持有股票，则查找下一个账户
		if quantAccount.HoldStockNumber == 0 {
			io.Infoln("账号[%s]持股票数量为0，不需要卖出股票", (*quantAccount).AccountName)
			continue
		}

		// 查询某个账号是否有退市的股票，如果有则卖出
		var quantStockTransactRecordArray model.QuantStockTransactRecordArray
		c.db.Raw("select qstr.* from quant_stock_transact_record qstr "+
			"join stock_info si_ on si_.code_=qstr.stock_code and si_.last_transaction_date is not null and si_.last_transaction_date=to_date(?, 'yyyy-mm-dd') "+
			"where qstr.account_name=? and qstr.sell_date is null and qstr.sell_price is null and qstr.sell_amount is null",
			transactionDate, quantAccount.AccountName).Scan(&quantStockTransactRecordArray)
		for _, quantStockTransactRecord := range quantStockTransactRecordArray {
			// 查询股票
			var stockTransactionDataAll model.StockTransactionDataAll
			c.db.Raw("select * from stock_transaction_data_all t "+
				"where t.code_ = ? and t.date_=to_date(?, 'yyyy-mm-dd')", quantStockTransactRecord.StockCode, transactionDate).Scan(&stockTransactionDataAll)

			// 由于这个是退市或者摘牌的股票，因此一定要卖掉
			if stockTransactionDataAll.ID == 0 {
				c.db.Raw("select * from "+
					"(select * from stock_transaction_data_all t where t.code_ = ? and t.date_ < to_date(?, 'yyyy-mm-dd') "+
					"order by t.date_ desc) std where rownum <= 1", quantStockTransactRecord.StockCode, transactionDate).Scan(&stockTransactionDataAll)
				io.Infoln("股票[%s]在日期[%s]退市或者摘牌，因此强行卖掉这只股票", quantStockTransactRecord.StockCode, transactionDate)
			}

			// 卖出
			// 更新quant_stock_transact_record表的sell_date、sell_price和sell_amount字段
			c.db.Exec("update quant_stock_transact_record t "+
				"set t.sell_date = to_date(?, 'yyyy-mm-dd'), t.sell_price  = ?, t.sell_amount = t.buy_amount,"+
				"t.stamp_duty = ROUND(t.buy_amount * "+fmt.Sprintf("%f", stockTransactionDataAll.OpenPrice)+" * "+fmt.Sprintf("%f", properties.QuantProperties_.StampDutyRate)+", 4),"+
				"t.registration_fee_when_sell = ?,"+
				"t.commission_when_sell = ? "+
				"where t.id_ = ?",
				transactionDate, stockTransactionDataAll.OpenPrice,
				util.CalculateRegistrationFee(quantStockTransactRecord.StockCode, quantStockTransactRecord.BuyAmount),
				util.CalculateCommission(stockTransactionDataAll.OpenPrice, quantStockTransactRecord.BuyAmount),
				quantStockTransactRecord.ID)

			// 更新quant_stock_transact_record表的profit_and_loss和profit_and_loss_rate字段
			c.db.Exec("update quant_stock_transact_record t "+
				"set t.profit_and_loss = ROUND((t.sell_price * t.sell_amount) - (t.buy_price * t.buy_amount), 4), "+
				"t.profit_and_loss_rate = (t.sell_price - t.buy_price) / t.buy_price * 100 "+
				"where t.id_ = ?", quantStockTransactRecord.ID)
		}

	}
}
